﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Kohvik.Kohvikuteenus;
using System.Xml;

namespace Kohvik {

    public partial class Upload : System.Web.UI.Page {

        ServiceClient klient = new ServiceClient();
        char[] oldChars = new char[] {' ', 'ü', 'Ü', 'õ', 'Õ', 'ö', 'Ö', 'ä', 'Ä', 'š', 'Š', 'ž', 'Ž'};
        char[] newChars = new char[] { '_', 'y', 'Y', '6', '6', '8', '8', '2', '2', 's', 'S', 'z', 'Z' };

        protected void Page_Load(object sender, EventArgs e) {        
            if (Session["kasutaja_ID"] != null && klient.isSuperAdmin(Session["kasutaja_ID"].ToString())) {
                //tegemist on adminniga, midagi peita pole vaja
            }
            else if (Session["kasutaja_ID"] != null && Session["kohviku_ID"] != null) {
                int tmp;
                if (int.TryParse(Session["kasutaja_ID"].ToString(), out tmp) && int.TryParse(Session["kohviku_ID"].ToString(), out tmp)) {
                    //tegemist on kohvikupidajaga, kellel on õigus enda kohvikut muuta
                    DropDownList1.Visible = false;
                }
                else {
                    //sessioonis on mingi crap
                    Panel1.Visible = false;
                }
            }
            else {
                //kasutajat pole sisse logitud ja seega ei näita kontrolle
                Panel1.Visible = false;
            }
            
            if (IsPostBack)
                return;

            List<EntityKohvik> list = klient.getEntityKohvikList();
            Dictionary<int, string> dic = new Dictionary<int, string>();

            foreach (EntityKohvik item in list) {
                dic.Add(item.Kohvik_ID, item.Nimi);
            }

            DropDownList1.DataSource = dic;
            DropDownList1.DataTextField = "value";
            DropDownList1.DataValueField = "key";
            DropDownList1.DataBind();
        }


        protected void UploadButton_Click(object sender, EventArgs e) {
            int kohvikID;
            if (Session["kasutaja_ID"] != null && klient.isSuperAdmin(Session["kasutaja_ID"].ToString())) {
                kohvikID = Convert.ToInt32(DropDownList1.SelectedItem.Value);
            }
            else if (Session["kasutaja_ID"] != null && Session["kohviku_ID"] != null) {
                int tmp;
                if (int.TryParse(Session["kasutaja_ID"].ToString(), out tmp) && int.TryParse(Session["kohviku_ID"].ToString(), out kohvikID)) {
                                    
                }
                else {
                    //sessioonis on mingi crap
                    return;
                }
            }
            else {
                return;
            }

            EntityKohvik kohvik;
            try {
                kohvik = klient.getEntityKohvikById(kohvikID);
                if (kohvik == null) {
                    StatusLabel.Text = "problem loading cafeteria";
                    return;
                }
            }
            catch (Exception) {
                StatusLabel.Text = "problem loading cafeteria";
                return;
            }

            if (FileUploadControl.HasFile) {
                try {
                    string filename = Path.GetFileName(FileUploadControl.FileName);
                    string filepath = "/Gallery/" + replaceChars(kohvik.Nimi) + "/";
                    string localpath = Server.MapPath("") + filepath;

                    if (!Directory.Exists(localpath)) {
                        Directory.CreateDirectory(localpath);
                        Directory.CreateDirectory(localpath + "thumbs/");
                    }
                    else {
                        if (File.Exists(localpath + filename)) {
                            StatusLabel.Text = "A file with that name already exists, choose another";
                            return;
                        }
                    }                    

                    FileUploadControl.SaveAs(localpath + filename);
                    File.Copy(localpath + filename, localpath + "thumbs/" + filename);
                    StatusLabel.Text = "Upload status: File uploaded!";
                    writeXML(kohvik, filepath, filename, tb_nimi.Text, tb_kirjeldus.Text);
                }
                catch (Exception ex) {
                    StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }
        }


        private string replaceChars(string kohvikuNimi) {
            //asendame igasugused täpitähed ja tühikud
            for (int i = 0; i < oldChars.Length; i++) {
                kohvikuNimi = kohvikuNimi.Replace(oldChars[i], newChars[i]);
            }
            return kohvikuNimi;
        }
        

        private void writeXML(EntityKohvik kohvik, string filepath, string filename, string title, string desc) {
            XmlDocument xmlDoc = new XmlDocument();
            try {
                xmlDoc.Load(Server.MapPath("~/Gallery/images.xml"));
            }
            catch (FileNotFoundException) {
                StatusLabel.Text = "could not find XML file";
                return;
            }

            XmlNode n_album;
            XmlElement root = xmlDoc.DocumentElement;
            n_album = root.SelectSingleNode("album[@title='" + kohvik.Nimi + "']");

            if (n_album == null) {
                n_album = xmlDoc.CreateNode(XmlNodeType.Element, "album", null);
                XmlAttribute n_title = xmlDoc.CreateAttribute("title");
                XmlAttribute n_desc = xmlDoc.CreateAttribute("description");
                XmlAttribute n_source = xmlDoc.CreateAttribute("source");
                n_title.Value = kohvik.Nimi;
                n_desc.Value = kohvik.Nimi + " pildialbum";
                n_source.Value = filepath + filename;
                n_album.Attributes.Append(n_title);
                n_album.Attributes.Append(n_desc);
                n_album.Attributes.Append(n_source);

                root.AppendChild(n_album);
            }

            XmlNode n_slide = xmlDoc.CreateNode(XmlNodeType.Element, "slide", null);
            XmlAttribute n_slidetitle = xmlDoc.CreateAttribute("title");
            XmlAttribute n_slidedesc = xmlDoc.CreateAttribute("description");
            XmlAttribute n_slidesource = xmlDoc.CreateAttribute("source");
            XmlAttribute n_slidethumb = xmlDoc.CreateAttribute("thumbnail");

            n_slidetitle.Value = title;
            n_slidedesc.Value = desc;
            n_slidesource.Value = filepath + filename;
            n_slidethumb.Value = filepath + "thumbs/" + filename;

            n_slide.Attributes.Append(n_slidetitle);
            n_slide.Attributes.Append(n_slidedesc);
            n_slide.Attributes.Append(n_slidesource);
            n_slide.Attributes.Append(n_slidethumb);

            n_album.AppendChild(n_slide);
            xmlDoc.Save(Server.MapPath("~/Gallery/images.xml"));
        }

    }

}